<?php
namespace addons\yalimedia\service;

class Fav
{

    public $model;

    public function __construct()
    {
        $this->model = new \app\admin\model\yalimedia\Fav();
    }

    /**
     * 收藏操作
     */
    public function act($type,$item_id,$user_id){
        if($favInfo = $this->model->where(['type'=>$type,'item_id'=>$item_id,'user_id'=>$user_id])->find()){
            $favInfo->delete();
            return ['is_fav'=>0];
        }else{
            $model = new \app\admin\model\yalimedia\Fav();
            $model->save([
                'type'=>$type,
                'item_id'=>$item_id,
                'user_id'=>$user_id
            ]);
            return ['is_fav'=>1];
        }
    }

    /**
     * 获取收藏列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getFavList($user_id,$page,$limit){
        $count = $this->model
            ->alias("fav")
            ->join("yalimedia_course course","fav.item_id=course.id and fav.type = 1")
            ->where(['fav.user_id'=>$user_id])
            ->count();
        if($page){
            $data = $this->model
                ->alias("fav")
                ->field("course.*")
                ->join("yalimedia_course course","fav.item_id=course.id and fav.type = 1")
                ->where(['fav.user_id'=>$user_id])
                ->page($page,$limit)->order("weigh asc")->select();
        }else{
            $data = $this->model
                ->alias("fav")
                ->field("course.*")
                ->join("yalimedia_course course","fav.item_id=course.id and fav.type = 1")
                ->where(['fav.user_id'=>$user_id])
                ->order("weigh asc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }


}